package main

import (
	"flag"
	"fmt"
	"io"
	"os"

	"app/docs"
	"app/internal/middleware"
	"app/internal/router"
	"app/pkg/config"

	swaggerfiles "github.com/swaggo/files"

	"github.com/gin-gonic/gin"
	ginSwagger "github.com/swaggo/gin-swagger"
)

//	@title			cep API
//	@version		1.0
//	@description	This is a sample server celler server.
//	@termsOfService	http://swagger.io/terms/

//	@contact.name	cep
//	@contact.email	9696060233@qq.com
func main() {
	flag.Parse()
	f, err := initLogsFile()
	if err != nil {
		panic(err)
	}
	if gin.Mode() == gin.DebugMode {
		gin.DefaultWriter = io.MultiWriter(f, os.Stdout)
		docs.SwaggerInfo.Host = "127.0.0.1:27000"
	} else {
		docs.SwaggerInfo.Host = config.Config.App.ServerIP + ":27000"
		docs.SwaggerInfo.Schemes = []string{"http"}
		gin.DefaultWriter = io.MultiWriter(f)
	}
	r := gin.Default()

	r.Use(middleware.CorsMiddleware())
	r.Use(middleware.SharedParamsMiddleware())
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerfiles.Handler))
	//注册路由
	router.RegisterApiRouters(r)
	r.Run(":27000")
}

func initLogsFile() (f *os.File, err error) {
	launchPath := "logs/launch.log"
	// 记录到文件。
	_, err = os.Open(launchPath)
	if err != nil {
		//创建目录
		err = os.MkdirAll("logs", 0777)
		if err != nil {
			fmt.Printf("%s", err)
			return
		}
		f, err = os.Create(launchPath)
		if err != nil {
			fmt.Println(err)
			return
		}
	} else {
		f, _ = os.OpenFile(launchPath, os.O_APPEND|os.O_RDWR, 0777)
	}
	return
}
